package view_server

import (
	"bigdevops/src/common"
	"bigdevops/src/config"
	"bigdevops/src/models"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/xanzy/go-gitlab"
	"go.uber.org/zap"
	"strconv"
)

func listGitlabProjects(c *gin.Context) {
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)
	gc := c.MustGet(common.GIN_CTX_CICD_GITLAB).(*gitlab.Client)
	projects, _, err := gc.Projects.ListProjects(&gitlab.ListProjectsOptions{})
	if err != nil {
		msg := fmt.Sprintf("通过gitlab拉取projects列表出错:%v", err.Error())
		sc.Logger.Error(msg, zap.Error(err))
		common.FailWithMessage(msg, c)
		return
	}
	ss := []*common.CommonSelectOneItemValueInt{}
	for _, project := range projects {
		ss = append(ss, &common.CommonSelectOneItemValueInt{
			Value: project.ID,
			Label: project.PathWithNamespace,
		})
	}
	common.OkWithData(ss, c)
	return
}

func listGitlabTagsByProjectId(c *gin.Context) {
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)
	gc := c.MustGet(common.GIN_CTX_CICD_GITLAB).(*gitlab.Client)
	id := c.Param("id")

	// 先 去db中根据id找到这个对象
	intVar, _ := strconv.Atoi(id)
	tags, _, err := gc.Tags.ListTags(intVar, &gitlab.ListTagsOptions{})
	if err != nil {
		msg := fmt.Sprintf("通过gitlab拉取projects列表出错:%v", err.Error())
		sc.Logger.Error(msg, zap.Error(err))
		common.FailWithMessage(msg, c)
		return
	}
	ss := []*common.FromKvOneItem{}
	for _, tag := range tags {
		ss = append(ss, &common.FromKvOneItem{
			Value: tag.Name,
			Key:   tag.Name,
		})
	}
	common.OkWithData(ss, c)
	return
}

func listGitlabTagsByCicdItemId(c *gin.Context) {
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)
	gc := c.MustGet(common.GIN_CTX_CICD_GITLAB).(*gitlab.Client)
	id := c.Param("id")

	// 先 去db中根据id找到这个对象
	intVar, _ := strconv.Atoi(id)
	dbCicdItem, err := models.GetCicdDeployItemById(intVar)
	if err != nil {
		sc.Logger.Error("根据id找服务发布项错误", zap.Any("服务发布项", id), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}

	tags, _, err := gc.Tags.ListTags(dbCicdItem.GitlabProjectId, &gitlab.ListTagsOptions{})
	if err != nil {
		msg := fmt.Sprintf("通过gitlab拉取projects列表出错:%v", err.Error())
		sc.Logger.Error(msg, zap.Error(err))
		common.FailWithMessage(msg, c)
		return
	}
	ss := []*common.CommonSelectOneItem{}
	for _, tag := range tags {
		ss = append(ss, &common.CommonSelectOneItem{
			Label: fmt.Sprintf("%v %v ", dbCicdItem.GitlabRepository, tag.Name),
			Value: tag.Name,
		})
	}
	common.OkWithData(ss, c)
	return
}
